import os
import requests
import json
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get API key from environment variables
API_KEY = os.getenv("DEEPSEEK_API_KEY")
if not API_KEY or API_KEY == "your_api_key_here":
    print("Please set your DeepSeek API key in the .env file")
    exit(1)

# DeepSeek API endpoint
API_URL = "https://api.deepseek.com/v1/chat/completions"

def generate_response(messages, model="deepseek-chat", max_tokens=1000):
    """
    Generate a response from the DeepSeek API using conversation history
    
    Args:
        messages (list): List of message objects with role and content
        model (str): The model to use (default: deepseek-chat)
        max_tokens (int): Maximum number of tokens to generate
        
    Returns:
        dict: The API response
    """
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
    
    data = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens
    }
    
    try:
        response = requests.post(API_URL, headers=headers, data=json.dumps(data))
        response.raise_for_status()  # Raise an exception for HTTP errors
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling DeepSeek API: {e}")
        return None

def main():
    print("DeepSeek API Conversation Interface")
    print("Type 'exit' to quit or 'clear' to start a new conversation")
    print("-" * 50)
    
    # Initialize conversation history
    conversation = []
    
    while True:
        user_input = input("\nYou: ")
        
        if user_input.lower() == "exit":
            print("Goodbye!")
            break
        
        if user_input.lower() == "clear":
            conversation = []
            print("Conversation history cleared.")
            continue
        
        # Add user message to conversation history
        conversation.append({"role": "user", "content": user_input})
        
        print("\nGenerating response...")
        response = generate_response(conversation)
        
        if response and "choices" in response:
            assistant_message = response["choices"][0]["message"]["content"]
            # Add assistant response to conversation history
            conversation.append({"role": "assistant", "content": assistant_message})
            print(f"\nDeepSeek: {assistant_message}")
        else:
            print("\nFailed to get a response from the API. Please check your API key and try again.")

if __name__ == "__main__":
    main() 